import { Context } from 'koa';
import KoaRouter from 'koa-router';
import CardList from '@/models/cardList';
import { validate } from '@/middleware/validate';
import Joi from 'joi';
import { v4 as uuidv4 } from 'uuid';
import { CreateCardListRequest, UpdateCardListRequest } from '@/types/route';
export default (router: KoaRouter) => {

    // 获取卡片列表数据
    router.get('/cardList', async (ctx: Context) => {
        try {
            // 使用聚合查询一次性获取卡片列表及其关联的卡片数据
            const cardListsWithCards = await CardList.aggregate([
                { $sort: { order: 1 } },
                {
                    $lookup: {
                        from: 'cards',
                        localField: 'listId',
                        foreignField: 'listId',
                        pipeline: [
                            { $sort: { order: 1 } },
                            { $project: { _id: 0, __v: 0, version: 0 } }
                        ],
                        as: 'cards'
                    }
                },
                { $project: { _id: 0, __v: 0, version: 0 } }
            ]);
            
            ctx.setResponse(cardListsWithCards, '获取卡片列表成功');
        } catch{ 
            ctx.status = 500;
            ctx.setResponse(null, '获取卡片列表失败', 500);
        }
    });

    // 创建卡片列表
    router.post('/cardList',
        validate(Joi.object({
            title: Joi.string().required().messages({
                'string.empty': '标题不能为空',
                'any.required': '标题是必填项'
            })
        })),
        async (ctx: Context) => {
            try {
                const { title } = ctx.request.body as CreateCardListRequest;
                const listId = uuidv4();
                
                // 使用事务创建卡片列表
                const newCardList = await CardList.createCardListWithTransaction(title, listId);
                ctx.setResponse(newCardList, '创建卡片列表成功');
            } catch (error) {
                ctx.status = 500;
                // 根据错误类型设置不同的错误信息
                const errorMessage = error instanceof Error ? error.message : '创建卡片列表失败';
                ctx.setResponse(null, errorMessage, 500);
            }
        }
    );

    // 修改卡片列表
    router.put('/cardList/:listId',
        validate(Joi.object({
            title: Joi.string().messages({
                'string.empty': '标题不能为空'
            }),
            order: Joi.number().integer().min(0).messages({
                'number.base': '顺序必须是数字',
                'number.integer': '顺序必须是整数',
                'number.min': '顺序不能小于0'
            })
        })),
        async (ctx: Context) => {
            try {
                const { listId } = ctx.params;
                const { title, order } = ctx.request.body as UpdateCardListRequest;

                // 查找目标卡片列表
                const targetList = await CardList.findOne({ listId });
                if (!targetList) {
                    ctx.status = 404;
                    return ctx.setResponse(null, '卡片列表不存在', 404);
                }

                const updateData: { title?: string; order?: number } = {};
                if (title) updateData.title = title;

                if (typeof order === 'number') {
                    // 获取所有卡片列表并按order排序
                    const allLists = await CardList.find().sort({ order: 1 });
                    const oldOrder = targetList.order;
                    const newOrder = Math.min(order, allLists.length - 1);

                    // 更新受影响的卡片列表的order（添加当前列表ID过滤）
                    if (newOrder > oldOrder) {
                        await CardList.updateOrderForBackwardMove(targetList.listId, oldOrder, newOrder);
                    } else if (newOrder < oldOrder) {
                        await CardList.updateOrderForForwardMove(targetList.listId, oldOrder, newOrder);
                    }
                    updateData.order = newOrder;
                }

                // 更新目标卡片列表，使用乐观锁机制
                const updatedList = await CardList.findOneAndUpdate(
                    { listId, version: targetList.version },
                    { ...updateData, $inc: { version: 1 } },
                    { new: true }
                );

                if (!updatedList) {
                    ctx.status = 409;
                    return ctx.setResponse(null, '数据已被其他用户修改，请刷新后重试', 409);
                }

                ctx.setResponse(updatedList, '修改卡片列表成功');
            } catch {
                ctx.status = 500;
                ctx.setResponse(null, '修改卡片列表失败', 500);
            }
        }
    );

    // 删除卡片列表
    router.delete('/cardList/:listId', async (ctx: Context) => {
        try {
            const { listId } = ctx.params;

            // 查找目标卡片列表
            const targetList = await CardList.findOne({ listId });
            if (!targetList) {
                ctx.status = 404;
                return ctx.setResponse(null, '卡片列表不存在', 404);
            }

            // 删除目标卡片列表，使用乐观锁机制
            const deleteResult = await CardList.deleteOne({ listId, version: targetList.version });
            
            if (deleteResult.deletedCount === 0) {
                ctx.status = 409;
                return ctx.setResponse(null, '数据已被其他用户修改，请刷新后重试', 409);
            }

            // 更新其他卡片列表的order
            await CardList.updateMany(
                { order: { $gt: targetList.order } },
                { $inc: { order: -1 } }
            );

            ctx.setResponse(null, '删除卡片列表成功');
        } catch {
            ctx.status = 500;
            ctx.setResponse(null, '删除卡片列表失败', 500);
        }
    });
}